﻿
// **************************************************************************
//    Class Created by element109 July 2010
//    for use by Mick Doherty (Dotnetrix)
//    http://dotnetrix.co.uk/
//
//    ...for GlassUI (an AeroGlass UI Library)
//    http://glassui.codeplex.com/
// **************************************************************************

using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Windows.Forms;
using GlassUI.Design;

namespace GlassUI
{
    [Designer(typeof(Design.AutoSizeControlDesigner))]
    public abstract class GlassAutoSizeControlBase : GlassControlBase
    {
        private AutoSizeMode autoSizeMode = AutoSizeMode.GrowAndShrink;

        [Browsable(true), EditorBrowsable(EditorBrowsableState.Always)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        [GlassUIDescription("ControlAutoSizeDescr", "System.Windows.Forms")]
        public override bool AutoSize
        {
            get { return base.AutoSize; }
            set
            {
                base.AutoSize = value;
                OnAutoSizeChanged();
            }
        }

        [DefaultValue(typeof(AutoSizeMode), "GrowAndShrink")]
        [GlassUIDescription("ControlAutoSizeModeDescr", "System.Windows.Forms")]
        [SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")]
        public AutoSizeMode AutoSizeMode
        {
            get { return autoSizeMode; }
            set
            {
                if (autoSizeMode != value)
                {
                    autoSizeMode = value;
                    OnAutoSizeModeChanged();
                }
            }
        }

        protected override void OnSizeChanged(EventArgs e)
        {
            base.OnSizeChanged(e);
            if (this.AutoSize)
            {
                Size sz = this.GetPreferredSize(this.Size);
                if (this.AutoSizeMode == AutoSizeMode.GrowOnly)
                {
                    sz = new Size(Math.Max(this.Size.Width, sz.Width), Math.Max(this.Size.Height, sz.Height));
                }
                this.Size = sz;
            }
        }

        protected override void OnFontChanged(EventArgs e)
        {
            base.OnFontChanged(e);
            this.OnSizeChanged(EventArgs.Empty);
        }

        protected override void OnTextChanged(EventArgs e)
        {
            base.OnTextChanged(e);
            this.OnSizeChanged(EventArgs.Empty);
        }

        #region Virtual methods

        protected virtual void OnAutoSizeChanged()
        {
            this.OnSizeChanged(EventArgs.Empty);
        }

        protected virtual void OnAutoSizeModeChanged()
        {
            this.OnSizeChanged(EventArgs.Empty);
        }
        #endregion
    }
}
